package com.hzjh.base.ext.frame

import androidx.lifecycle.viewModelScope
import com.hzjh.base.ext.ai.AiUtils
import com.hzjh.base.ext.data.UserConfigs
import com.hzjh.base.frame.BaseViewModel
import com.hzjh.base.http.Request
import com.hzjh.base.ext.route.RouteUrl
import com.hzjh.base.router.ext.navigationTo
import com.hzjh.base.style.view.loading.LoadingDialogManager
import com.hzjh.base.utils.function.toJson
import com.hzjh.base.utils.other.ActivityStackManage
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

open class JHBaseVM : BaseViewModel() {
    fun <T> makeCall(ifNeedLoading:Boolean=false,ifCanCancelLoading:Boolean=true, buildRequest: Request<T>.() -> Unit) {

        val commonRequest = Request<T>().apply(buildRequest)

        commonRequest.onStart {
            if(ifNeedLoading) {
                MainScope().launch {
                    LoadingDialogManager.get().showLoading(ActivityStackManage.currentActivity())
                }
            }
        }

        commonRequest.onError {
            errMsg.value = it
            commonRequest.originError?.invoke(it)
        }

        commonRequest.onResponse { data ->
            data?.let {
                when (data.code) {
                    200 -> {
                        commonRequest.originResponse?.invoke(data.toJson())
                        data.data.let {
                            commonRequest.success?.invoke(data.data)
                        } ?: return@let
                    }
                    410000, 410001, 410002, 401 -> {
                        UserConfigs.loginOut()
                        navigationTo(RouteUrl.LOGIN_ACTIVITY)
                    }
                    else -> commonRequest.error?.invoke(data.message)
                }
            } ?: run {
                commonRequest.error?.invoke("Error")
            }
        }

        commonRequest.onRealResponse{
            commonRequest.realSuccess?.invoke(it?:"")
        }

        commonRequest.onComplete {
            if(ifCanCancelLoading) {
                MainScope().launch {
                    LoadingDialogManager.get().dismissLoading()
                }
            }
        }

        commonRequest.toRequest(viewModelScope)

    }

    fun sendMsg(msg: String,aiCallBack: ((String) -> Unit)?=null){
        AiUtils.sendMsg(viewModelScope,msg,aiCallBack)
    }
}